using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ViScript.Core;
using ViScript.Core.Exceptions;
using ViScript.Core.ParsedSentence;

namespace ViScript.Example
{
    public partial class MainForm : Form, IOutput
    {
        private readonly Engine engine;

        public MainForm()
        {
            InitializeComponent();
            engine = Engine.CreateEngine(new ExampleLanguage(this));
        }

        public void WriteLine(string message)
        {
            outputTextBox.Text = message + Environment.NewLine + outputTextBox.Text;
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            Clear();
        }

        private void Clear()
        {
            outputTextBox.Text = string.Empty;
        }

        private void executeButton_Click(object sender, EventArgs e)
        {
            Clear();
            try
            {
                engine.Execute(CreateSenteceReader());
            }
            catch (ViScriptParsingException)
            {
            }
            catch (ViScriptExecutionException ex)
            {
                WriteLine(ex.ToString());
            }
        }

        private SentenceReader CreateSenteceReader()
        {
            return new SentenceReader("no file", new StringReader(scriptTextBox.Text));
        }

        private void showParsingResultButton_Click(object sender, EventArgs e)
        {
            List<IParsedSentence> parsedSentences = engine.Parse(CreateSenteceReader());
            ParsingResultForm parsingResultForm = new ParsingResultForm(Engine.EscapeStrategy);
            parsingResultForm.SetParsingResult(parsedSentences);
            parsingResultForm.Show(this);
        }
    }
}